<?php

//Check key and 
//Create the new EmailVerification PostBackControl
class ApplicantEmailVerification extends PostBackControl {
	var $User;
					
	
	function ApplicantEmailVerification (&$Context) {
		$this->Name = 'ApplicantEmailVerification';
		$this->ValidActions = array('ApplicantEmailVerification');
		$this->Constructor($Context);
		
		$this->PostBackValidated = 0;
		$VerificationKey = ForceIncomingString('k', '');
		$UserID = ForceIncomingInt('u', 0);
					
		if ($this->IsPostBack) {
			
			// Set up the page
			global $Banner, $Foot;
			$Banner->Properties['CssClass'] = 'Apply';
			$Foot->CssClass = 'Apply';
			$this->Context->PageTitle = $this->Context->GetDefinition('AntiSPamToolbox_email');
			
			
			$UserManager = $this->Context->ObjectFactory->NewContextObject($Context, 'UserManager');
			if ( !$this->User = $UserManager->GetUserById($UserID) ) $this->Context->WarningCollector->Add($this->Context->GetDefinition('AntiSPamToolbox_ApplicationNotFound'));
			
			if ($this->PostBackAction == 'ApplicantEmailVerification' && $this->Context->WarningCollector->Count() == 0) {
				
				//check the user is already a member of the forum
				if ( $this->User->RoleID > 1 ) $this->Context->WarningCollector->Add($Context->GetDefinition('AntiSPamToolbox_AlreadyValidated'));
				else {
					//check if the user need has a Verification Key pending, and if the key in the database in the input is the same
					
					//Get the userkeyfrom the database					 
					$EmailVerification = $this->Context->ObjectFactory->NewContextObject($this->Context, "EmailVerification", $this->User);
					$EmailVerification->GetKey();
					
					//Check if the key exist
					if (!$EmailVerification->VerificationKey) $this->Context->WarningCollector->Add($this->Context->GetDefinition('AntiSPamToolbox_NoKeyInDB'));
					
					//Check if the key from the DB and form the input are different
					if ( $EmailVerification->VerificationKey != $VerificationKey ) $this->Context->WarningCollector->Add($this->Context->GetDefinition('AntiSPamToolbox_WrongKey'));
					else {
						//The are the same
						//so Change role
						$Urh = $this->Context->ObjectFactory->NewObject($this->Context, 'UserRoleHistory');
						$Urh->UserID = $this->User->UserID;
						$Urh->AdminUserID = 0;
						$Urh->RoleID = $this->Context->Configuration['ANTI_SPAM_TOOLBOX_EMAIL_ROLE'];
						if ($this->Context->Configuration['ANTI_SPAM_TOOLBOX_EMAIL_APROVE']) {
							$Urh->Notes = $this->Context->GetDefinition('RegistrationAccepted');
							} else {
							//or at least let the admin that still have to aprove the membership that the Email has been checked
							//*will have to find an other way to do it
							$Urh->Notes = $this->Context->GetDefinition('AntiSPamToolbox_PendingApproval');
						}
						if ($UserManager->AssignRole($Urh, 1)) $this->PostBackValidated = 1;
						
						//delete the Vefification key
						$EmailVerification->DeleteKey();
							
						//Let admins know a user is ready for approval
						if (!$this->Context->Configuration['ANTI_SPAM_TOOLBOX_EMAIL_APROVE']) {
							$s = $this->Context->ObjectFactory->NewContextObject($this->Context, 'SqlBuilder');
							$s->SetMainTable('User', 'u');
							$s->AddJoin('Role', 'r', 'RoleID', 'u', 'RoleID', 'inner join');
							$s->AddWhere('r', 'PERMISSION_RECEIVE_APPLICATION_NOTIFICATION', '', 1, '=');
							$s->AddWhere('u', 'SendNewApplicantNotifications', '', 1, '=');
							$s->AddSelect(array('Name', 'Email'), 'u');
							$Administrators = $this->Context->Database->Select($s, $this->Name, 'ApplicantEmailVerification', 'An error occurred while retrieving administrator email addresses.', 0);
							// Fail silently if an error occurs while notifying administrators
						
							// Get the email body
							$File = $this->Context->Configuration['LANGUAGES_PATH']
								.$this->Context->Configuration['LANGUAGE']
								.'/email_applicant.txt';
							$EmailBody = @file_get_contents($File);
							
							if ($EmailBody && $Administrators) {
								$EmailBody = str_replace(
									array(
										"{applicant_name}",
										"{applicant_email}",
										"{application_url}"
									),
									array(
										$this->User->Name,
										$this->User->Email,
										ConcatenatePath(
											$this->Context->Configuration['BASE_URL'],
											GetUrl($this->Context->Configuration, 'account.php', '', 'u', $this->User->UserID)
										)
									),
									$EmailBody
								);
								
						
								if ($this->Context->Database->RowCount($Administrators) > 0) {
									$e = $this->Context->ObjectFactory->NewContextObject($this->Context, 'Email');
									$e->HtmlOn = 0;
									$e->ErrorManager = &$this->Context->ErrorManager;
									$e->WarningCollector = &$this->Context->WarningCollector;
									$e->AddFrom($this->User->Email, $this->User->Name);
									$AdminEmail = '';
									$AdminName = '';
									while ($Row = $this->Context->Database->GetRow($Administrators)) {
										$AdminEmail = ForceString($Row['Email'], '');
										$AdminName = ForceString($Row['Name'], '');
										if ($AdminEmail != '') $e->AddRecipient($AdminEmail, $AdminName);
									}
									$e->Subject = $this->Context->GetDefinition("NewApplicant");
									$e->Body = $EmailBody;						
									$e->Send(0);
								}
							}
						}
					} 
				}
			}
		}
	}
	
	function Render() {
		if($this->IsPostBack) {
			$this->CallDelegate('PreValidPostBackRender');
			echo '<div class="FormComplete">
			<h2>'.$this->Context->GetDefinition('AntiSPamToolbox_email').'</h2>';
			$this->Render_Warnings();
			if ($this->PostBackValidated) {
				echo '<ul>';
				if ($this->Context->Configuration['ANTI_SPAM_TOOLBOX_EMAIL_APROVE']) {
					echo '<li>'.$this->Context->GetDefinition('AntiSPamToolbox_MembershipAccepted').'</li>
					<li><a href="'.GetUrl($this->Context->Configuration, $this->Context->SelfUrl).'">'.$this->Context->GetDefinition('BackToSignInForm').'</a></li>';
				}
				else {
					echo '<li>'.$this->Context->GetDefinition('AntiSPamToolboxDonePendingApproval').'</li>';
				}
				echo '</ul>';
			}
			echo '</div>';
			$this->CallDelegate('PostValidPostBackRender');
		}
	}
}

?>